package cn.example.vip.mall.user.interceptor;

import cn.example.vip.mall.user.util.JwtTokenUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器
 */
@Component
public class AuthHandlerInterceptor implements HandlerInterceptor {
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String token = request.getHeader("token");
		// 验证token
		if(token == null){
			System.err.println("缺少 token 认证信息,跳转登录界面:" + request.getRequestURL());
			response.sendRedirect("/user/login");
			return false;
		}
		// 验证 token
		
		System.out.println("header token:" + token);
		boolean auth = JwtTokenUtils.verity(token);
		System.out.println("认证结果:" + auth);
		return auth;
		
//		return HandlerInterceptor.super.preHandle(request, response, handler);
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
	}
}
